package com.mamcharge.file.web;

import com.alibaba.fastjson.JSON;
import com.mamcharge.file.annotation.LxRateLimit;
import com.mamcharge.file.config.RouteConfig;
import com.mamcharge.file.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@Slf4j
@RestController
public class FileController {

    @Resource
    private FileService fileService;
    @Autowired
    private RouteConfig routeConfig;
    /**
     * 文件上传
     *
     * @param files
     * @param filePath
     * @return
     */
    @PostMapping("saveFiles")
    public String save(@RequestParam(value = "files", required = false) MultipartFile[] files, String filePath) {
        Map<String, Object> returnMap = new HashMap<>();
        if (files == null) {
            log.warn("Client no upload files");
            returnMap.put("status", 1);
        } else {
            String[] fileNames = Arrays.stream(files).map(file -> fileService.saveFile(file, filePath)).toArray(String[]::new);
            returnMap.put("status", 0);
            returnMap.put("files", fileNames);
        }
        return JSON.toJSONString(returnMap);
    }

    /**
     * 文件下载
     *
     * @param filePath
     * @return
     */
    @GetMapping("downFile")
    @LxRateLimit(perSecond=1,timeOut=0)
    public void down(HttpServletResponse response, String filePath) throws FileNotFoundException {
        String fileName=filePath.substring(filePath.lastIndexOf("/")+1,filePath.length());
        String disk=routeConfig.getHardDisk();
        String extName = fileName.substring(fileName.lastIndexOf(".") + 1);
        // 下载本地文件
        String path=disk+"/"+filePath;
        // 读到流中
        InputStream inStream = new FileInputStream(path);// 文件的存放路径
        // 设置输出的格式
        response.reset();
        if(this.inArray(routeConfig.getImageType(),"."+extName)){
            response.setContentType("text/html; charset=UTF-8");
            response.setContentType("image/"+extName);
        }
        //视频类型文件
        else if(this.inArray(routeConfig.getVideoType(),"."+extName)){
            response.setContentType("bin");
            response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        }
        //文档类型文件
        else if(this.inArray(routeConfig.getDocumentType(),"."+extName)){
            response.setContentType("bin");
            response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        }
        else {
            response.setContentType("bin");
            response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        }

        //
        // 循环取出流中的数据
        byte[] b = new byte[100];
        int len;
        try {
            while ((len = inStream.read(b)) > 0)
                response.getOutputStream().write(b, 0, len);
            inStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 判断数组中是否包含某个元素
     * @param array 类型的数组
     * @param element 被检查的类型
     * @return
     */
    private boolean inArray(String[] array,String element) {
        boolean flag = false;
        for(String type : array) {
            if(element.equals(type)){
                flag = true;
                break;
            }
        }
        return flag;
    }

    /**
     * 单个文件上传
     * @param file
     * @param filePath
     * @return
     */
    @PostMapping("singleSave")
    public String singleSave(@RequestParam(value = "file",required = false) MultipartFile file,String filePath) {
        Map<String, Object> returnMap = new HashMap<>();
        if(file == null) {
            log.warn("Client no upload files");
            returnMap.put("status", 1);
        }else {
            returnMap.put("status", 0);
            returnMap.put("file",fileService.saveFile(file,filePath));
        }
        return JSON.toJSONString(returnMap);
    }

    /**
     * 删除文件
     * @param filePath
     * @return
     */
    @PostMapping("dropFile")
    public  String dropFile(String filePath) {
        Map<String,Object> returnMap = new HashMap<>();
        String returnStr = fileService.dropFile(filePath);
        log.info(returnStr+"and dropfile:"+filePath);
        if("successful operation".equals(returnStr)) {
            returnMap.put("status", 0);
        }else {
            returnMap.put("status", 1);
        }
        return JSON.toJSONString(returnMap);
    }

}
